package handle

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"website/model"
	"website/utils"
)

func CreateManagers(c *gin.Context)  {
	var m model.Managers
	if err := c.ShouldBind(&m); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    -1,
			"message": err.Error(),
		})
		return
	}

	if len(m.Phone) != 0 {
		if !utils.VerifyMobileFormat(m.Phone) {
			c.JSON(http.StatusOK, gin.H{
				"code":    -1,
				"message": "手机号码格式有误，请输入正确的手机号！",
			})
			return
		}
	}
	if !utils.VerifyEmailFormat(m.Email) {
		c.JSON(http.StatusOK, gin.H{
			"code":    -1,
			"message": "邮箱格式有误，请输入正确的邮箱！",
		})
		return
	}
	if err := m.CreateManagers(); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"message": "创建失败, error: " + err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 1,
		"message": "创建成功",
	})
}

func FetchAllManagers(c *gin.Context)  {
	var m model.Managers
	data, err := m.FetchAllManagers()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"message": "获取后台管理用户失败, error: " + err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 1,
		"results": data,
	})
}

func UpdateManagers(c *gin.Context)  {
	var m model.Managers
	if err := c.ShouldBind(&m); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    -1,
			"message": err.Error(),
		})
		return
	}

	id, _ := strconv.ParseInt(c.Param("id"), 10, 64)
	if err := m.UpdateManagers(id); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"message": "更新失败, error: " + err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 1,
		"message": "更新成功",
	})
}
